package cn.bluethink.graphical;

import cn.bluethink.utile.ColorUtil;
import cn.bluethink.utile.GraphicalUtil;

import java.awt.*;

public class Polyline extends Polygon {

    public Polyline() {
    }

    public Polyline(Polyline polyline) {
        for (Point point : polyline.points){
            points.add(point);
        }
    }

    @Override
    public String type() {
        return "polyline";
    }

    /**
     * 画折线方法
     * @param c
     */
    @Override
    public void draw(Graphics c) {
        int[] xPoints = GraphicalUtil.getXAndY(points).get("x");
        int[] yPoints = GraphicalUtil.getXAndY(points).get("y");
        c.setColor(ColorUtil.getColor());
        c.drawPolyline(xPoints,yPoints,points.size());
    }

    @Override
    public void drawAsSelect(Graphics c) {

        if (points.size() < 2) {
            return;
        }

        Color oldColor= c.getColor();
        c.setColor(Color.YELLOW);

        int[] xPoints = GraphicalUtil.getXAndY(points).get("x");
        int[] yPoints = GraphicalUtil.getXAndY(points).get("y");
        c.drawPolyline(xPoints,yPoints,points.size());
        c.setColor(oldColor);
    }

    @Override
    public int hitTest(Point pt) {
        if (points.size() < 2){
            return 0;
        }
        for (int i = 0; i < points.size() - 1; i++) {
            if( Math.abs(pt.getX() - points.get(i).getX()) <= SEL_TOLERANCE && Math.abs(pt.getY() - points.get(i).getY()) <= SEL_TOLERANCE ){
                return i + 1;
            } else if (Math.abs(pt.getX() - points.get(i + 1).getX()) <= SEL_TOLERANCE && Math.abs(pt.getY() - points.get(i + 1).getY()) <= SEL_TOLERANCE){
                return i + 2;
            } else if (pt.getX() >= (points.get(i).getX() > points.get(i + 1).getX() ? points.get(i + 1).getX() : points.get(i).getX()) &&
                    pt.getX() <= (points.get(i).getX() < points.get(i + 1).getX() ? points.get(i + 1).getX() : points.get(i).getX()) &&
                    pt.getY() >= (points.get(i).getY() > points.get(i + 1).getY() ? points.get(i + 1).getY() : points.get(i).getY()) &&
                    pt.getY() <= (points.get(i).getY() < points.get(i + 1).getY() ? points.get(i + 1).getY() : points.get(i).getY()) &&
                    ponintToLineDistance(pt,points.get(i),points.get(i + 1)) <= SEL_TOLERANCE){
                return -1;
            }
        }
        return 0;
    }
    /**
     * 计算当前鼠标选中点和直线距离
     * @param point
     * @param start
     * @param end
     * @return
     */
    private double ponintToLineDistance(Point point, Point start, Point end) {
       return Math.abs((start.getY() - end.getY()) * point.getX() - (start.getX()- end.getX()) * point.getY() + end.getY() * start.getX() - start.getY() * end.getX()) / Math.sqrt((start.getX() - end.getX()) * (start.getX() - end.getX()) + (start.getY() - end.getY()) *(start.getY() - end.getY()));
    }

}
